import axios from 'axios'
import router from '@/router'
import store from '@/store'
import to from 'await-to-js'
import { Toast } from 'vant'
import { refreshToken } from '@/api/user'
const instance = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})

// 添加请求拦截器
instance.interceptors.request.use(function (config) {
  const token = store.getters.token
  if (token) config.headers.Authorization = `Bearer ${token}`
  return config
}, function (error) {
  return Promise.reject(error)
})

// 添加响应拦截器
instance.interceptors.response.use(function (response) {
  return response
}, async function async (error) {
  if (error.response && error.response.status === 401) {
    const [err, res] = await to(refreshToken(store.state.user.refreshToken))
    if (err) {
      store.commit('user/REMOVE_TOKEN')
      Toast.fail('token失效')
      router.replace('/login?returnUrl=' + encodeURIComponent(router.currentRoute.fullPath))
    } else {
      store.commit('user/SET_TOKEN', { current_token: res.data.data.token })
      // 再次发送上次失败的请求, err.config 是之前失败的请求配置
      return instance(error.config)
    }
  }
  return Promise.reject(error)
})
export default ({ url, method = 'get', params, data, headers }) => {
  return to(instance({ url, method, params, data, headers }))
}
